﻿using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenFaq.AcceptanceTests.StepHelpers;
using TechTalk.SpecFlow;
using WatiN.Core;

using Table = TechTalk.SpecFlow.Table;

namespace OpenFaq.AcceptanceTests.Steps
{
    [Binding]
    public class PageInteraction
    {

		[Given("I click the \"(.*)\" link")]
		public void GivenIClickALinkNamed(string linkName)
		{
			ClickALinkNamed(linkName);
		}

    	private void ClickALinkNamed(string linkName)
    	{
    		var link = WebBrowser.Current.Link(Find.ByText(linkName));

    		if (!link.Exists)
    			Assert.Fail(string.Format("Could not find '{0}' link on the page", linkName));

    		link.Click();
    	}

    	[When("I click the \"(.*)\" link")]
        public void WhenIClickALinkNamed(string linkName)
        {
			ClickALinkNamed(linkName);
        }



		[Given("I click the \"(.*)\" button")]
		public void GivenIClickAButtonWithValue(string buttonValue)
		{
			ClickAButtonWithValue(buttonValue);
		}

    	private void ClickAButtonWithValue(string buttonValue)
    	{
    		var button = WebBrowser.Current.Button(Find.ByValue(buttonValue));

    		if (!button.Exists)
    			Assert.Fail(string.Format("Could not find '{0}' button on the page", buttonValue));

    		button.Click();
    	}


    	[When("I click the \"(.*)\" button")]
        public void WhenIClickAButtonWithValue(string buttonValue)
    	{
    		ClickAButtonWithValue(buttonValue);
    	}



		[When(@"I complete the form with the following information:")]
		public void WhenICompleteTheFormWithTheFollowingInformation(Table table)
		{
			foreach (var tableRow in table.Rows)
			{
				var field = WebBrowser.Current.TextField(Find.ByName(tableRow["Field"]));

				if (!field.Exists)
					Assert.Fail(string.Format("Could not find {0} field on the page", field));

				field.TypeText(tableRow["Value"]);
			}
		}

    }
}